#include "config.h"
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include <gconf/gconf-client.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
//#include <libgnomevfs/gnome-vfs.h>

#include "totem-uri.h"
#include "video-utils.h"
#include "totem-plugin.h"
#include "totem-private.h"
#include "totem.h"
#include "totem-sidebar.h"
#include "totem-playlist.h"
#include "bacon-video-widget.h"

#include "lrcshow.h"
#include "lmp-debug.h"
#include "lmp-lyric-download.h"
#include "totem-lrc.h"

static void totem_lrc_plugin_init		(TotemLrcPlugin *plugin);
static gboolean impl_activate		(TotemPlugin *plugin, TotemObject *totem, GError **error);
static void impl_deactivate		(TotemPlugin *plugin, TotemObject *totem);

TOTEM_PLUGIN_REGISTER(TotemLrcPlugin, totem_lrc_plugin)

Totem *lrc_totem = NULL;

static void
totem_lrc_plugin_class_init(TotemLrcPluginClass *klass)
{
	lmp_debug("");
//	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	TotemPluginClass *plugin_class = TOTEM_PLUGIN_CLASS (klass);

	plugin_class->activate = impl_activate;//每次totem启动插件时impl_activate被调用。
	plugin_class->deactivate = impl_deactivate;//每次totem卸载插件时impl_deactivate被调用。
	plugin_class->create_configure_dialog = dialog_config;
}

static void
totem_lrc_plugin_init (TotemLrcPlugin *plugin)
{
	lmp_debug("");
	plugin->win = NULL;
	plugin->lrc_win = NULL;
}

gchar *lrc_plugin_get_artist_title(gboolean bl)
{
	GValue value = { 0, };
	gchar *tmp0 = NULL,*tmp1 = NULL;
	Totem *totem = lrc_totem;
	gboolean flag = FALSE;

	bacon_video_widget_get_metadata (totem->bvw, bl?BVW_INFO_ARTIST:BVW_INFO_TITLE, &value);
	tmp0 = g_value_dup_string (&value);
	g_value_unset (&value);

	if(!tmp0){
		if(bl)
			return g_strdup("");
		if(totem){
			lmp_debug("Geting title");
			tmp0 = totem_get_short_title(totem);
			flag = TRUE;
		}
		if(!tmp0)
			return g_strdup("");
	}
	tmp1 = encode_to_self(tmp0);
	g_free(tmp0);
	tmp0 = all_to_utf8(tmp1,-1);
	g_free(tmp1);
	if(flag){
		int i = strlen(tmp0)-1;
		while(i>0){
			if(tmp0[i]=='.'){
				tmp0[i]=0;
				break;
			}
			i--;
		}
		lmp_debug("Got title:%s.",tmp0);
	}
	lmp_debug("exit.");
	return tmp0;
}

gchar *lrc_plugin_get_lrcname(void)
{
	GValue value = { 0, };
	gchar *title = NULL,*artist = NULL;
	Totem *totem = lrc_totem;
	bacon_video_widget_get_metadata (totem->bvw,BVW_INFO_ARTIST,&value);
	artist = g_value_dup_string (&value);
	g_value_unset (&value);
	bacon_video_widget_get_metadata (totem->bvw,BVW_INFO_TITLE,&value);
	title = g_value_dup_string (&value);
	g_value_unset (&value);
	if(!title)
		title = totem_get_short_title(totem);
	gchar *tmp0 = g_strdup_printf("%s_%s.lrc",artist,title);
	g_free(title);
	g_free(artist);
	gchar *tmp1 = encode_to_self(tmp0);
	g_free(tmp0);
	tmp0 = all_to_utf8(tmp1,-1);
	g_free(tmp1);
	return tmp0;
}

/*
每次播放一个文件,totem都会发出一个"file-opened"信号
我们利用这一点知道新的工作开始了
*/
static void
totem_lrc_plugin_file_opened (TotemObject *totem,
					   const char *mrl,
					   TotemLrcPlugin *plugin)
{
	lmp_debug("coming.");
	int i=0;
	char *title,*artist;
	gchar *str = NULL,*lrc=NULL;

	TotemLrcPlugin *pi;
	pi = TOTEM_LRC_PLUGIN (plugin);
	if(!pi->win)return;

	str = g_filename_from_uri(mrl,NULL,NULL);//uri式的路径转换成一般形式
	lrc = g_strdup_printf("%s%c%c%c%c",str,0,0,0,0);
	g_free(str);

	while(lrc[i]){
		if(lrc[i++]=='.'){
			sprintf(lrc+i,"%s","lrc");
			break;
		}
	}
	
	if(lrc[i-1]!='.')
		sprintf(lrc+i,"%s",".lrc");

	artist = lrc_plugin_get_artist_title(TRUE);
	title = lrc_plugin_get_artist_title(FALSE);
	if(pi->lrc_win&&GTK_IS_WIDGET(pi->lrc_win)){
		gtk_window_set_title(GTK_WINDOW(pi->lrc_win),title);
	}
	lmp_debug("artist:%s title: %s.",artist,title);

//	lyric_filename_set_to(lrc,LRC_SET);

	is_lrc_in_buff = FALSE;
	is_down_ok = FALSE;
	gtk_widget_hide(lrc_selection_dialog(NULL));
	load_lrc_file(lrc,artist,title);///歌词秀从这里开始,载入歌词,建立线程搜索/下载歌词等
	g_free(lrc);
	lmp_debug("exit.");
}

/*
处理"file_closed"信号
*/
static void
totem_lrc_plugin_file_closed (TotemObject *totem,
					   TotemLrcPlugin *plugin)
{
	lmp_debug("close run");
	is_down_ok = FALSE;
	is_lrc_in_buff = FALSE;
//	lyric_filename_set_to(NULL,LRC_WD);
	lmp_debug("close exit");
}

static void
totem_lrc_plugin_mata(TotemObject *totem,
				const char *artist, 
				const char *title, 
				const char *album,
				TotemLrcPlugin *plugin)
{
	lmp_debug("");
	g_signal_stop_emission_by_name(totem,"metadata-updated");
	gchar *tl = lrc_plugin_get_artist_title(FALSE);
//	gtk_window_set_title(plugin->win,tl);//这行没有显示出效果来。奇怪ing
	char *lyricfile = lrc_get_lrc_fullpath();
	if(!is_lrc_in_buff&&access(lyricfile,F_OK)==0){
		is_down_ok = TRUE;
		lmp_debug("Send a reload lyric signal .");
		if(set_and_get_timeout(0)==0)
			kill(getpid(),sig_reload_lrc);
		if(plugin->lrc_win)
			gtk_window_set_title(plugin->lrc_win,tl);
	}
	g_free(tl);
	g_free(lyricfile);

}

/*
插件的准配工作开始了
我们totem_lrc_plugin_class_init中作了指定.
*/
static gboolean
impl_activate (TotemPlugin *plugin,
	       TotemObject *totem,
	       GError **error)
{
	lmp_debug("");
	TotemLrcPlugin *pi;
//	GtkWidget *menu;
	gchar *path = NULL;

	pi = TOTEM_LRC_PLUGIN (plugin);
	pi->totem = totem;
	pi->win = totem_get_main_window(totem);
	path = totem_plugin_find_file(plugin,"lrc.glade");
	pi->lrc_pad = load_lrc_ui(path);
	g_free(path);

	if(!g_thread_supported()) g_thread_init(NULL);
/*
  menu = status_menu(pi->win);
  path = totem_plugin_find_file(plugin,"mycalc.ico");
  pi->status = status_icon(menu,path);
  g_free(path);
*/
	lrc_show = TRUE;
	lrc_totem = totem;
//	lrc_config_save_load(FALSE);

	gchar *ui = totem_plugin_find_file((TotemPlugin*)pi,"down.glade");
	lrc_selection_dialog(ui);
	g_free(ui);
	lrc_show_win_or_side(plugin);
//	lmp_debug_set_flag(TRUE);

	signal(sig_reload_lrc,sig_handler_reload);

	/*  我们强烈要求自己要参加信号的处理  */

	pi->open_id = g_signal_connect (G_OBJECT (totem),
							"file-opened",
							G_CALLBACK (totem_lrc_plugin_file_opened),
							plugin);

	pi->close_id = g_signal_connect (G_OBJECT (totem),
							"file-closed",
							G_CALLBACK (totem_lrc_plugin_file_closed),
							plugin);
/*
	g_signal_connect (pi->win,
				"destroy-event",
				G_CALLBACK (on_totem_win),
				NULL);

	g_signal_connect (GTK_OBJECT(pi->win),
				"delete-event",
				G_CALLBACK (on_totem_win),
				NULL);
*/
	pi->mata_id = g_signal_connect_after (G_OBJECT (totem),
								"metadata-updated",
								G_CALLBACK (totem_lrc_plugin_mata),
								plugin);
	if(totem_is_playing(totem)||totem_is_paused(totem)){
		is_down_ok = TRUE;
		kill(getpid(),sig_reload_lrc);
	}
	return TRUE;
}

/*
我们不用插件了,也要做好善后
须在totem_lrc_plugin_class_init作指定
*/
static void
impl_deactivate	(TotemPlugin *plugin,
		 TotemObject *totem)
{
	is_down_ok = FALSE;
	is_lrc_in_buff = FALSE;
	lmp_debug("");
	TotemLrcPlugin *pi;
	pi = TOTEM_LRC_PLUGIN (plugin);

	is_lrc_in_buff = FALSE;
	is_down_ok = FALSE;

//	lrc_config_save_load(TRUE);
	///撤销自定义的事件处理
	g_signal_handler_disconnect (G_OBJECT (totem), pi->open_id);
	g_signal_handler_disconnect (G_OBJECT (totem), pi->close_id);
	g_signal_handler_disconnect (G_OBJECT (totem), pi->mata_id);
//  pi->win = NULL;
	if(pi->lrc_win)
		gtk_widget_destroy (pi->lrc_win);
	if(pi->lrc_pad)
		gtk_widget_destroy (pi->lrc_pad);
	//  g_object_unref(pi->status);
}

void lrc_show_win_or_side(TotemPlugin *plugin)
{
	TotemLrcPlugin *pi;
	pi = TOTEM_LRC_PLUGIN (plugin);
	char *yes_no = lrc_get_value("side_ro_win");
	lmp_debug("");
	if(yes_no&&*yes_no=='1'){
		lmp_debug("lyric show in a signal window");
		g_object_ref(pi->lrc_pad);
		if(!pi->lrc_win)
			totem_remove_sidebar_page (lrc_totem,"lrcshow");
		g_object_ref(pi->lrc_pad);///这行必须如此
		pi->lrc_win = lrc_show_lrc_in_win(pi->lrc_pad);
		gtk_widget_show_all(GTK_WIDGET(pi->lrc_win));
	}else{
		lmp_debug("lyric show in side");
		if(pi->lrc_win){
			gtk_container_remove(pi->lrc_win,pi->lrc_pad);
			g_object_ref(pi->lrc_pad);///这行必须如此
			gtk_widget_destroy(pi->lrc_win);
			pi->lrc_win = NULL;
		}
		totem_add_sidebar_page (lrc_totem, "lrcshow", _("LrcShow"), pi->lrc_pad);
		totem_sidebar_set_current_page(lrc_totem,"lrcshow",TRUE);
	}
	if(yes_no)
		g_free(yes_no);
	lmp_debug("exit .");
}

void on_button_ok(GtkButton *button,GtkEntry *entry)
{
	const char *lrcdir = gtk_entry_get_text(entry);
	lrc_set_lyric_dir((char*)lrcdir);
	GtkWidget *top = gtk_widget_get_toplevel(GTK_WIDGET(button));
	gtk_widget_destroy(top);
}

void on_button_add(GtkButton *button,GtkEntry *entry)
{
	GtkWidget *dialog;

	dialog = gtk_file_chooser_dialog_new (_("Open Folder"),
				      gtk_widget_get_toplevel(GTK_WIDGET(button)),
				      GTK_FILE_CHOOSER_ACTION_OPEN|GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER,
				      GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
				      GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
				      NULL);

	gtk_window_set_position(GTK_WINDOW(dialog),GTK_WIN_POS_CENTER_ON_PARENT);
	gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dialog),lrc_get_lyric_dir());
	if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT){
		char *filename;
		filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
		gtk_entry_set_text(entry,filename);
		g_free (filename);
	}
	gtk_widget_destroy (dialog);
}

void on_button_chk(GtkToggleButton *togglebutton,TotemPlugin *plugin)
{
	gboolean flag = gtk_toggle_button_get_active(togglebutton);
	if(!append_new_string_to_conffile("side_ro_win",flag?"1":"0"))
		g_warning("%s:%d",__FILE__,__LINE__);
	lrc_show_win_or_side(plugin);
}

/*
给我一个配置插件的机会吧!
*/

GtkWidget * dialog_config(TotemPlugin *plugin)
{
	GtkWidget *dialog  = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	GtkWidget *vbox = gtk_vbox_new(FALSE,2);
	GtkWidget *entry = gtk_entry_new();
	GtkWidget *hbox = gtk_hbox_new(FALSE,2);
	GtkWidget *chkbutton;

	GtkWidget *browser = gtk_button_new_from_stock(GTK_STOCK_ADD);
	GtkWidget *button = gtk_button_new_from_stock(GTK_STOCK_OK);
	chkbutton = gtk_check_button_new_with_mnemonic(_("Use a sigal window ."));
	GtkWidget *label = gtk_label_new(_("The path to save lrc files:"));

	gtk_misc_set_alignment(GTK_MISC(label),0,0);
	gtk_entry_set_text(GTK_ENTRY(entry),lrc_get_lyric_dir());
	char *flag = lrc_get_value("side_ro_win");
	gtk_toggle_button_set_active(chkbutton,flag&&*flag == '1'?TRUE:FALSE);
	if(flag)
		g_free(flag);

	gtk_box_pack_start(GTK_BOX(hbox),entry,TRUE,TRUE,0);
	gtk_box_pack_start(GTK_BOX(hbox),browser,FALSE,TRUE,0);

	gtk_box_pack_start(GTK_BOX(vbox),label,TRUE,TRUE,0);
	gtk_box_pack_start(GTK_BOX(vbox),hbox,TRUE,TRUE,0);
	gtk_box_pack_start(GTK_BOX(vbox),chkbutton,TRUE,TRUE,0);
	gtk_box_pack_start(GTK_BOX(vbox),button,TRUE,TRUE,0);

	gtk_container_add(GTK_CONTAINER(dialog),vbox);
	gtk_window_set_title(GTK_WINDOW(dialog),_("Configure"));
	gtk_window_set_resizable (GTK_WINDOW(dialog),FALSE);

	g_signal_connect(button,"clicked",G_CALLBACK(on_button_ok),entry);
	g_signal_connect(browser,"clicked",G_CALLBACK(on_button_add),entry);
	g_signal_connect(chkbutton,"toggled",G_CALLBACK(on_button_chk),plugin);

//	gtk_widget_set_parent(dialog,GTK_WIDGET(totem_get_main_window(lrc_totem)));
	gtk_window_set_position(GTK_WINDOW(dialog),GTK_WIN_POS_MOUSE/*GTK_WIN_POS_CENTER*/);
	gtk_window_set_skip_taskbar_hint(GTK_WINDOW(dialog),TRUE);
	gtk_widget_show_all(dialog);

	return dialog;
}

